/**
 * @author 0283000115
 * @date 2018年3月3日-下午2:32:37
 */
package com.zte.claa.inficombo.csa.app.controller;

import java.sql.Timestamp;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zte.claa.inficombo.csa.app.controller.ret.ApiResult;
import com.zte.claa.inficombo.csa.app.model.dev.ResourceShadow;
import com.zte.claa.inficombo.csa.app.model.redis.AlarmData;
import com.zte.claa.inficombo.csa.app.service.csa.impl.BaseCacheManager;
import com.zte.claa.inficombo.csa.app.service.rptparse.ParserContainer;
import com.zte.claa.inficombo.csa.app.util.JsonUtils;

import io.swagger.annotations.ApiOperation;

/**
 * @author 0283000115
 * 
 * 该controller仅用于接收中维世纪脱岗监测摄像头上报的告警数据.
 *
 */

@RestController
@RequestMapping("/csa/zwsj") 
public class ZWSJIpcAlarmRptController extends BaseController {
	// public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	
	public static final String ALARM_CODE = "1"; // 摄像头监测脱岗告警。
	
	// logger
	private Logger logger = LoggerFactory.getLogger(ZWSJIpcAlarmRptController.class);
	
	@Autowired
	private BaseCacheManager cacheManager;
	
	@Autowired
	private ParserContainer parserContainer;

    /**
     * 中维世纪告警上报
     * 
     * {	//报警推送消息
		"method": "alarm_msg_push",	
		"param": {
			"dev_id": "A402153844",	//设备ID
			"dev_type": "ipc,nvr",	//设备类型
			"channel": 1,			//关联视频通道id，IPC固定取1，nvr可配
			"status": "start,stop",	//报警状态：start开始报警，stop停止报警
			"type": "LeavingPost",  //报警类型：LeavingPost，离岗
			"subtype": "0",			//报警源通道id，默认为0
			"subtype_name": "name",	//报警源名称，默认为空
			"msg": "alarm details describe",			//报警提示消息
			"videoPath": "sd card or disk path",		//录像地址：需支持sd的设备
			"jpegBase64": "base64 data of jpeg data"	//base64编码的jpeg图片数据
		}
	}
 
     * @param request
     * @return 
     * @throws Exception
     */
	@ApiOperation(value = "脱岗告警推送", notes = "中维世纪摄像头脱岗告警推送")
	@RequestMapping(value={"/alarmrpt"})
	@ResponseBody
	public ApiResult<?> alarmrpt(HttpServletRequest request) throws Exception{		
		ApiResult<String> ret = new ApiResult<String>();
		String jsonStr = "";
		try{
			jsonStr = this.getJsonParam(request);
			logger.info("Receive json str: "+jsonStr);
			JSONObject json = new JSONObject(jsonStr);
			JSONObject paraJson = JsonUtils.getSubObject(json, "param");
			if(paraJson == null){
				logger.warn("There is no param parameter in rpt msg");
				ret.setRemark("无效的上报消息！");
				ret.setResult(ApiResult.RET_FAIL);
				return ret;
			}
			String devId = JsonUtils.getJsonAttrVal(paraJson, "dev_id", null);
			if(devId == null){
				logger.warn("DevId parameter is invalid!");
				ret.setRemark("设备编号无效！");
				ret.setResult(ApiResult.RET_FAIL);
				return ret;
			}
			ResourceShadow res = this.cacheManager.getRes(devId);
			if(res == null){
				logger.warn("Dev not exist!");
				ret.setRemark("设备不存在！");
				ret.setResult(ApiResult.RET_FAIL);
				return ret;
			}

			String dev_type = JsonUtils.getJsonAttrVal(paraJson, "dev_type", "");			
			String channel = JsonUtils.getJsonAttrVal(paraJson, "channel", "1");
			String status = JsonUtils.getJsonAttrVal(paraJson, "status", "");
			String type = JsonUtils.getJsonAttrVal(paraJson, "type", "");
			String subtype = JsonUtils.getJsonAttrVal(paraJson, "subtype", "0");
			String subtype_name = JsonUtils.getJsonAttrVal(paraJson, "subtype_name", "");
			String msg = JsonUtils.getJsonAttrVal(paraJson, "msg", "");
			
			StringBuffer addInfoBuf = new StringBuffer();
			addInfoBuf.append("设备类型：").append(dev_type);
			addInfoBuf.append(res.getRestypename()).append("; ");
			addInfoBuf.append("通道号：").append(channel).append("; ");
			addInfoBuf.append("状态值：").append(status).append("; ");
			addInfoBuf.append("消息类型：").append(type).append("; ");
			addInfoBuf.append("报警源名称：").append(subtype_name).append("[").append(subtype).append("]; ");
			addInfoBuf.append("报警信息：").append(msg).append("; ");
			
			// 构造Alarm
			AlarmData alarm = new AlarmData();
			alarm.setAlarmid("A"+Math.abs(UUID.randomUUID().getLeastSignificantBits()));
			alarm.setAlarmlevel(AlarmData.ALARM_LEVEL_1);
			alarm.setAlarmcode(ALARM_CODE);
			if("start".equalsIgnoreCase(status)){
				alarm.setTypeflag(AlarmData.TPFLAG_ALARM);
			} else {
				alarm.setTypeflag(AlarmData.TPFLAG_CLEAR);
			}
			if("LeavingPost".equalsIgnoreCase(type)){
				alarm.setTitle(res.getResname()+"-人员离岗告警");
			} else {
				alarm.setTitle(res.getResname()+"-其他告警");
			}
			alarm.setDeveui(devId);
			alarm.setDevtype(res.getRestype());
			alarm.setProjectid(res.getProjectid());
			alarm.setDevname(res.getResname());			
			alarm.setAlarmtime(new Timestamp(System.currentTimeMillis()));
			alarm.setDescp(addInfoBuf.toString());
			if(alarm.getTypeflag() == AlarmData.TPFLAG_CLEAR){
				alarm.setCleartime(new Timestamp(System.currentTimeMillis()));
			}
			alarm.setConfirmstate(AlarmData.CONFIRM_STATE_N);	
			alarm.setRemark(res.getRemark());
			// 发布告警.
			String alarmJson = JsonUtils.toJson(alarm);
			this.parserContainer.getAlarmPublisher().publishMessage(alarmJson);
			logger.info("[*^_^*]Publish alarm message ok: "+alarmJson);	

			ret.setRemark("success");
			ret.setResult(ApiResult.RET_SUCC);			
		}catch(Exception e){
			logger.error("alarmrpt msg process failed: "+jsonStr, e);
			ret.setRemark(e.getMessage());
			ret.setResult(ApiResult.RET_FAIL);
		}
		return ret;
	}

}
